package com.example.hunheandroid

import android.app.Application
import android.content.Context
import android.content.Intent
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.FlutterEngineGroup
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugins.BasePlugin

const val ENGINE_ID = "my_engine_id"

object FlutterLibrary {
    fun init(application: Application) {
        FlutterEngineManager.getInstance().init(application)
    }

    fun getEngine(): FlutterEngine? {
        return FlutterEngineManager.getInstance().getEngine()
    }

    fun startFlutterPage(context: Context) {
        val intent = FlutterActivity
            .withCachedEngine(ENGINE_ID)
            .build(context).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }
}

// FlutterEngineManager.kt
class FlutterEngineManager private constructor() {
    private lateinit var engineGroup: FlutterEngineGroup
    private var engine: FlutterEngine? = null

    companion object {
        private var instance: FlutterEngineManager? = null

        fun getInstance(): FlutterEngineManager {
            return instance ?: synchronized(this) {
                instance ?: FlutterEngineManager().also { instance = it }

            }
        }
    }

    fun init(application: Application) {
        engineGroup = FlutterEngineGroup(application)
        engine = engineGroup.createAndRunEngine(
            application,
            DartExecutor.DartEntrypoint.createDefault()
        )
        FlutterEngineCache.getInstance().put(ENGINE_ID, engine)
        engine!!.plugins.add(BasePlugin())

    }

    fun getEngine(): FlutterEngine? {
        return engine
    }

    fun destroyEngine() {
        engine?.destroy()
        engine = null
    }
}

